package com.myStruts.servlet;

import java.io.IOException;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.myStruts.action.BaseAction;
import com.myStruts.bean.XmlBean;
import com.myStruts.fromBean.BaseBean;
import com.myStruts.util.FullBean;

public class BaseServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;


	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String forward = "";
		try {
			String path = this.getPath(request.getServletPath());
			Map<String, XmlBean> map =(Map<String, XmlBean>)this.getServletContext().getAttribute("struts");
			XmlBean bean = map.get(path);
			if (bean != null && bean.getBeanClass() != null) {
				BaseBean bb = FullBean.full(bean.getBeanClass(), request);

				Class aClass = Class.forName(bean.getActionClass());
				BaseAction ba = (BaseAction) aClass.newInstance();
				forward = ba.execute(request, response, bb, bean.getActionForward());
			}

		} catch (Exception e) {
			System.out.println("系统异常");
			e.printStackTrace();
		}
		RequestDispatcher dis = request.getRequestDispatcher(forward);
		dis.forward(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

	private String getPath(String servletPath) {
		return servletPath.split("\\.")[0];
	}
}
